<?php
namespace module\index\controller;

use app\Controller;
use app\model\UserAddress as Model;
use app\model\City;

class Address extends Controller
{
    /**
     * 列表.
     * 
     */
    public function index()
    {
        $result = Model::scope('user')->withSearch(['status'], input('get.'))->order('update_at', 'DESC')
            ->field(['id', 'name', 'title', 'mobile', 'dist_id', 'address', 'postcode', 'default'])->paginate([
                'list_rows'=> input('get.pageSize/d', 10),
            ]);
        $items = $result->items();
        foreach($items as $k => $row){
            $items[$k]['areaText'] = City::labels($row['dist_id'], ['value' => 'code', 'label' => 'name']);
        }
        return json([
            'items' => $result->items(),
            'total' => $result->total()
        ]);        
    }
    /**
     * 详情.
     * 
     */
    public function read(int $id)
    {
        $model = Model::scope('user')->findOrFail($id);
        $model->areaText = City::labels($model->dist_id, ['value' => 'code', 'label' => 'name']);
        return json($model->toArray());    
    }
    /**
     * 保存.
     * 
     */
    public function save()
    {
        $model = new Model;
        $model->save($this->request->post());
        return json($model->toArray());
    }
    /**
     * 更新.
     * 
     * @param int $id
     */
    public function update(int $id)
    {
        $model = Model::scope('user')->findOrFail($id);
        $model->save($this->request->put());
        return json($model->toArray());
    }
    /**
     * 删除.
     * 
     * @param int $id
     */
    public function del(int $id)
    {
        $model = Model::scope('user')->findOrFail($id);
        $model->delete();
        return json($model->toArray());
    }
    /**
     * 删除.
     * 
     * @param int $id
     */
    public function default(int $id)
    {
        $model = Model::scope('user')->findOrFail($id);
        $model->save(['default' => [1, 0][$model->default]]);
        return json($model->toArray());
    }
}
